package com.eugeneMa.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 操作Cookie的工具类
 *
 * @author Eugenema
 * @date 2022/2/6 21:42
 */
public class CookieUtil {
    /** 日志 */
    private static Logger logger = Logger.getLogger(CookieUtil.class);

    /**
     * 添加cookie
     *
     * @author Eugenema
     * @date 2022/3/5 18:08
     *
     * @param key cookie的键
     * @param value cookie的值
     * @param path 路径，若为null，则不设置路径
     * @param expiry 有效时间，0立即过期、大于0则为有效时间、小于0则会话结束过期
     *
     **/
    public static void addCookie(HttpServletResponse response, String key, Object value, String path, int expiry) {
        /** cookie的值 */
        String content;
        if (value == null) {
            content = null;
        } else if (value instanceof String) {
            content = (String)value;
        } else {
            content = JSONObject.toJSONString(value);
        }

        /** 存入的Cookie */
        Cookie cookie = new Cookie(key, content);

        if (path != null) {
            cookie.setPath(path);
        }
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
    }

    /**
     * 通过键获取值
     *
     * @author Eugenema
     * @date 2022/2/6 21:42
     *
     * @param request 请求对象
     * @param name 要获取的键
     *
     * @return 获取到这个键对应的值，如果没有或出现异常，则返回空字符串
     **/
    public static String getCookieValue(HttpServletRequest request, String name) {
        try {
            //读取浏览器端所有的Cookie数据，返回Cookie的数组
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(name)) {
                        return cookie.getValue();
                    }
                }
            }
            return "";
        } catch (Exception e) {
            logger.error("获取Cookie【" + name + "】值出现异常！", e);
            return "";
        }
    }

    /**
     * 删除Cookie
     *
     * @author Eugenema
     * @date 2022/2/21 22:21
     *
     * @param cookieName 要删除的Cookie名字
     * @param path 路径
     *
     **/
    public static void deleteCookie(HttpServletResponse response, String cookieName, String path) {
        addCookie(response, cookieName, null, path, 0);
    }
}
